﻿using AutoMapper.Internal.Mappers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;

namespace Himp.Erp
{
    /// <summary>
    /// 药品目录
    /// </summary>
    public class DrugCatalogService : CrudAppService<DrugCatalog, DrugCatalogDto, Guid, DrugCatalogInput, DrugCatalogCreateOrUpdateDto, DrugCatalogCreateOrUpdateDto>, IDrugCatalogService
    {
        private IRepository<DrugCatalog, Guid> _drugCatalogRepository;

        public DrugCatalogService(IRepository<DrugCatalog, Guid> drugCatalogRepository) : base(drugCatalogRepository)
        {
            _drugCatalogRepository = drugCatalogRepository;
        }

        /// <summary>
        /// 获取药品目录列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public override async Task<PagedResultDto<DrugCatalogDto>> GetListAsync(DrugCatalogInput input)
        {
            var iQuery = await _drugCatalogRepository.GetQueryableAsync();

            if (input.Pi == 0)
            {
                var itemsDto = ObjectMapper.Map<List<DrugCatalog>, List<DrugCatalogDto>>(iQuery.ToList());

                return new PagedResultDto<DrugCatalogDto>(itemsDto.Count, itemsDto);
            }
            else
            {
                var totalCount = iQuery.Count();
                var items = iQuery.Page(input.Pi, input.Ps);
                var itemsDto = ObjectMapper.Map<List<DrugCatalog>, List<DrugCatalogDto>>(items.ToList());

                return new PagedResultDto<DrugCatalogDto>(totalCount, itemsDto);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public override async Task<DrugCatalogDto> CreateAsync(DrugCatalogCreateOrUpdateDto input)
        {
            var drugCatalog = ObjectMapper.Map<DrugCatalogCreateOrUpdateDto, DrugCatalog>(input);
            drugCatalog.ChrgitmType = new DrugCatalogAssocChrgitmType(input.ClncChrgitmTypeCode, input.ClncChrgitmTypeName);
            drugCatalog = await _drugCatalogRepository.InsertAsync(drugCatalog);

            return ObjectMapper.Map<DrugCatalog, DrugCatalogDto>(drugCatalog);
        }
    }
}
